﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace RrslLite
{
    public abstract class Batch
    {
        public IList<BatchCall> Calls { get; private set; }

        protected IList<Action<IEnumerable<BatchCallResult>>> CompletedActions { get; set; }

        protected Batch()
        {
            Calls = new List<BatchCall>();
            CompletedActions = new List<Action<IEnumerable<BatchCallResult>>>();
        }

        public virtual void WhenCompletedCall(Action<IEnumerable<BatchCallResult>> action)
        {
            CompletedActions.Add(action);
        }

        public virtual void Execute()
        {
            foreach (var batchCall in Calls)
            {
                batchCall.Call();
            }

            DoExecuteBatch();
        }

        protected abstract void DoExecuteBatch();

        protected virtual void OnCompleted(IEnumerable<BatchCallResult> results)
        {
            foreach (var completedAction in CompletedActions)
            {
                completedAction(results);
            }
        }
    }
}